package com.sunwayworld.basemodule.common.eptstorage.db;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class DynamicBeanHanderService {

    @Autowired
    private ApplicationContext applicationContext;
    
    public  <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }
    public Object getBean(String beanId) {
        return applicationContext.getBean(beanId);
    }
    public  <T> Map<String, T> getBeansOfType(Class<T> type) {
        return applicationContext.getBeansOfType(type);
    }
    public  boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }
    public  boolean isSingleton(String name) {
        return applicationContext.isSingleton(name);
    }
    public  Class<? extends Object> getType(String name) {
        return applicationContext.getType(name);
    }
    public  <T> T register(String name, Class<T> clazz, Object... args) {
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
        if (args.length > 0) {
            Object[] var4 = args;
            int var5 = args.length;
            for(int var6 = 0; var6 < var5; ++var6) {
                Object arg = var4[var6];
                beanDefinitionBuilder.addConstructorArgValue(arg);
            }
        }
        BeanDefinition beanDefinition = beanDefinitionBuilder.getRawBeanDefinition();
        BeanDefinitionRegistry beanFactory = (BeanDefinitionRegistry)applicationContext;
        beanFactory.registerBeanDefinition(name, beanDefinition);
        return applicationContext.getBean(name, clazz);
    }
    public  <T> T register(String name, Class<T> clazz, Map<String, Object> params) {
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
        if (params != null && params.size() > 0) {
            params.forEach((s, o) -> {
                beanDefinitionBuilder.addPropertyValue(s, o);
            });
        }
        BeanDefinition beanDefinition = beanDefinitionBuilder.getRawBeanDefinition();
        BeanDefinitionRegistry beanFactory = (BeanDefinitionRegistry)applicationContext;
        beanFactory.registerBeanDefinition(name, beanDefinition);
        return applicationContext.getBean(name, clazz);
    }

    public void destory(String beanId){
        BeanDefinitionRegistry beanFactory = (BeanDefinitionRegistry)applicationContext;
        beanFactory.removeBeanDefinition(beanId);
    }

}

